const CryptoJS = require('./aes.js');
/*
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */

/*
 * Configurable variables. You may need to tweak these to be compatible with
 * the server-side, but the defaults work in most cases.
 */
var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase        */
var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance   */
var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode      */

/*
 * These are the functions you'll usually want to call
 * They take string arguments and return either hex or base-64 encoded strings
 */
function hex_md5(s) {
    return binl2hex(core_md5(str2binl(s), s.length * chrsz));
}

function b64_md5(s) {
    return binl2b64(core_md5(str2binl(s), s.length * chrsz));
}

function str_md5(s) {
    return binl2str(core_md5(str2binl(s), s.length * chrsz));
}

function hex_hmac_md5(key, data) {
    return binl2hex(core_hmac_md5(key, data));
}

function b64_hmac_md5(key, data) {
    return binl2b64(core_hmac_md5(key, data));
}

function str_hmac_md5(key, data) {
    return binl2str(core_hmac_md5(key, data));
}

/*
 * Perform a simple self-test to see if the VM is working
 */
function md5_vm_test() {
    return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}

/*
 * Calculate the MD5 of an array of little-endian words, and a bit length
 */
function core_md5(x, len) {
    /* append padding */
    x[len >> 5] |= 0x80 << ((len) % 32);
    x[(((len + 64) >>> 9) << 4) + 14] = len;

    var a = 1732584193;
    var b = -271733879;
    var c = -1732584194;
    var d = 271733878;

    for (var i = 0; i < x.length; i += 16) {
        var olda = a;
        var oldb = b;
        var oldc = c;
        var oldd = d;

        a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936);
        d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
        c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
        b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
        a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
        d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
        c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
        b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
        a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
        d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
        c = md5_ff(c, d, a, b, x[i + 10], 17, -42063);
        b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
        a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
        d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
        c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
        b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);

        a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
        d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
        c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
        b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302);
        a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
        d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
        c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
        b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
        a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
        d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
        c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
        b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
        a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
        d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
        c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
        b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);

        a = md5_hh(a, b, c, d, x[i + 5], 4, -378558);
        d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
        c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
        b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
        a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
        d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
        c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
        b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
        a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
        d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222);
        c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
        b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
        a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
        d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
        c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
        b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651);

        a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844);
        d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
        c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
        b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
        a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
        d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
        c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
        b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
        a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
        d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
        c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
        b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
        a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
        d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
        c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
        b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551);

        a = safe_add(a, olda);
        b = safe_add(b, oldb);
        c = safe_add(c, oldc);
        d = safe_add(d, oldd);
    }
    return Array(a, b, c, d);

}


/*
 * These functions implement the four basic operations the algorithm uses.
 */
function md5_cmn(q, a, b, x, s, t) {
    return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b);
}

function md5_ff(a, b, c, d, x, s, t) {
    return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}

function md5_gg(a, b, c, d, x, s, t) {
    return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}

function md5_hh(a, b, c, d, x, s, t) {
    return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}

function md5_ii(a, b, c, d, x, s, t) {
    return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}

/*
 * Calculate the HMAC-MD5, of a key and some data
 */
function core_hmac_md5(key, data) {
    var bkey = str2binl(key);
    if (bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);

    var ipad = Array(16),
        opad = Array(16);
    for (var i = 0; i < 16; i++) {
        ipad[i] = bkey[i] ^ 0x36363636;
        opad[i] = bkey[i] ^ 0x5C5C5C5C;
    }

    var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
    return core_md5(opad.concat(hash), 512 + 128);
}

/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
function safe_add(x, y) {
    var lsw = (x & 0xFFFF) + (y & 0xFFFF);
    var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
    return (msw << 16) | (lsw & 0xFFFF);
}

/*
 * Bitwise rotate a 32-bit number to the left.
 */
function bit_rol(num, cnt) {
    return (num << cnt) | (num >>> (32 - cnt));
}

/*
 * Convert a string to an array of little-endian words
 * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
 */
function str2binl(str) {
    var bin = Array();
    var mask = (1 << chrsz) - 1;
    for (var i = 0; i < str.length * chrsz; i += chrsz)
        bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (i % 32);
    return bin;
}

/*
 * Convert an array of little-endian words to a string
 */
function binl2str(bin) {
    var str = "";
    var mask = (1 << chrsz) - 1;
    for (var i = 0; i < bin.length * 32; i += chrsz)
        str += String.fromCharCode((bin[i >> 5] >>> (i % 32)) & mask);
    return str;
}

/*
 * Convert an array of little-endian words to a hex string.
 */
function binl2hex(binarray) {
    var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
    var str = "";
    for (var i = 0; i < binarray.length * 4; i++) {
        str += hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8 + 4)) & 0xF) +
            hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8)) & 0xF);
    }
    return str;
}

/*
 * Convert an array of little-endian words to a base-64 string
 */
function binl2b64(binarray) {
    var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    var str = "";
    for (var i = 0; i < binarray.length * 4; i += 3) {
        var triplet = (((binarray[i >> 2] >> 8 * (i % 4)) & 0xFF) << 16) |
            (((binarray[i + 1 >> 2] >> 8 * ((i + 1) % 4)) & 0xFF) << 8) |
            ((binarray[i + 2 >> 2] >> 8 * ((i + 2) % 4)) & 0xFF);
        for (var j = 0; j < 4; j++) {
            if (i * 8 + j * 6 > binarray.length * 32) str += b64pad;
            else str += tab.charAt((triplet >> 6 * (3 - j)) & 0x3F);
        }
    }
    return str;
}


//Base64鍔犲瘑
function base64encode(input) {
    var output = "";
    var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i = 0;

    input = _utf8_encode(input);
    while (i < input.length) {

        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
            enc4 = 64;
        }

        output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4);

    }

    return output;
}

function _utf8_encode(string) {
    string = string.replace(/\r\n/g, "\n");
    var utftext = "";

    for (var n = 0; n < string.length; n++) {

        var c = string.charCodeAt(n);

        if (c < 128) {
            utftext += String.fromCharCode(c);
        } else if ((c > 127) && (c < 2048)) {
            utftext += String.fromCharCode((c >> 6) | 192);
            utftext += String.fromCharCode((c & 63) | 128);
        } else {
            utftext += String.fromCharCode((c >> 12) | 224);
            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
            utftext += String.fromCharCode((c & 63) | 128);
        }

    }
    return utftext;
}

function isJSON(str) {
    if (typeof str == 'string') {
        try {
            var obj = JSON.parse(str);
            if (typeof obj == 'object' && obj) {
                return true;
            } else {
                return false;
            }

        } catch (e) {
            console.log('error锛�' + str + '!!!' + e);
            return false;
        }
    }
}
//鐢熸垚uuid
function getUuid(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [],
        i;
    radix = radix || chars.length;

    if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
        var r;

        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';

        for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
                r = 0 | Math.random() * 16;
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
        }
    }
    return uuid.join('');
}

function dateFormat(obj, fmt) {
    var o = {
        "M+": obj.getMonth() + 1, //鏈堜唤 
        "d+": obj.getDate(), //鏃� 
        "h+": obj.getHours(), //灏忔椂 
        "m+": obj.getMinutes(), //鍒� 
        "s+": obj.getSeconds(), //绉� 
        "q+": Math.floor((obj.getMonth() + 3) / 3), //瀛ｅ害 
        "S+": obj.getMilliseconds() //姣 
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (obj.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : ((((RegExp.$1.length == 3 && k == "S+") ? "000" :
                "00") + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}
//鑾峰彇娴忚鍣ㄦ寚绾瑰苟杩涜base64鍔犲瘑澶勭悊浠ュ強url缂栫爜
function getFingerPrint() {
    return encodeURIComponent(base64encode(getBrowserInfo()));
}

function getSystem() {
    const res = wx.getSystemInfoSync()
    if (res.platform === 'android') {
        return '0';
    } else if (res.platform === 'ios') {
        return '1';
    } else {
        return '2';
    }
}

function getCurUrl() {
	var pages = getCurrentPages() //鑾峰彇鍔犺浇鐨勯〉闈�
	var currentPage = pages[pages.length - 1] //鑾峰彇褰撳墠椤甸潰鐨勫璞�
	var url = currentPage.route //褰撳墠椤甸潰url

	var options = currentPage.options
	if (!!options) {
		var param = '';
		for (let key in options) {
			var str = key + '=' + options[key];
			param = param + str + '&'
		}
		url = url + '?' + param
		url = url.substr(0, url.length - 1)
	}
	return url;
}




/**
 * 鑾峰彇鏈€澶栧眰绐楀彛娴忚鍣ㄧ殑淇℃伅,鑾峰彇涓嶅埌灏辫繑鍥炰负绌�
 */
 function getBrowserInfo() {
	try {
		const res = wx.getSystemInfoSync()
		var str = res.brand + '@@' +
			res.model + '@@' +
			res.pixelRatio + '@@' +
			res.screenWidth + '@@' +
			res.screenHeight + '@@' +
			res.language + '@@' +
			res.version + '@@' +
			res.system + '@@' +
			res.platform + '@@' +
			res.SDKVersion + '@@' +
			res.benchmarkLevel + '@@' +
			new Date().getTimezoneOffset()
		var BrowserInfo = encodeURIComponent(res.brand + '@@' + res.version + '@@' + res.system + '@@' + hex_md5(str));
		return BrowserInfo
	} catch (e) {
		// Do something when catch error
	}

}

//鍒涘缓鍏叡鍙傛暟
let optparam = {
    v: "20220713",
    traceId: '',
    msgId: '',
    timestamp: dateFormat(new Date(), 'yyyyMMddhhmmssSSS'),
    userInformation: getBrowserInfo(),
    businessType: '8',
    ywType: 'CT',
    isLoading: true,
    maskPhone: '',
    httpsPreGetmobile: {
        test01: "https://testcert.cmpassport.com:7009/h5/httpsPreGetmobile",
        pro: "https://verify.cmpassport.com/h5/httpsPreGetmobile"
    },

    // 鐢典俊棰勫彇鍙�
    getTelecomUrl: {
        test01: 'http://120.197.235.102/h5/onekeylogin/getNewTelecomPhonescrip',
        pro: 'https://www.cmpassport.com/h5/onekeylogin/getNewTelecomPhonescrip'
    },
    // 鐢典俊鍥炶皟
    getTelecomToken: {
        test01: 'http://120.197.235.102/h5/onekeylogin/CTCallback',
        pro: 'https://www.cmpassport.com/h5/onekeylogin/CTCallback'
    },
    // 鑱旈€氶鍙栧彿
    getUnicomUrl: {
        test01: 'http://120.197.235.102//h5/onekeylogin/getNewUnicomPhonescrip',
        pro: 'https://www.cmpassport.com/h5/onekeylogin/getNewUnicomPhonescrip'
    },
    // 鑱旈€氬洖璋�
    getUnicomToken: {
        test01: 'http://120.197.235.102//h5/onekeylogin/CUCallback',
        pro: 'https://www.cmpassport.com/h5/onekeylogin/CUCallback'
    },
    logReport: {
        pro: "https://log-h5.cmpassport.com:9443/log/logReport"
    },
    getToken: {
        test01: 'http://120.197.235.102/h5/onekeylogin/authGetToken',
        pro: 'https://www.cmpassport.com//h5/onekeylogin/authGetToken'
    },
    jssdkLog: {
        traceid: '',
        appScene: '1',
        wxappid: '',
        appid: '',
        networkType: '',
        clientType: '',
        costtime_GetOwnerAppValidate: '',
        CMrequestTime_PreGetmobile: '',
        CMresponseTime_PreGetmobile: '',
        CM_resultCode: '',
        CTrequestTime_PreGetmobile: '',
        CTresponseTime_PreGetmobile: '',
        CT_resultCode: '',
        CUrequestTime_PreGetmobile: '',
        CUresponseTime_PreGetmobile: '',
        CU_resultCode: '',
        polling_PreGetmobile: '',
    },
    authPageOpt: null
}



let getToken = {
    //鑾峰彇缃戠粶绫诲瀷
    getConnection: function (data) {
        var net = null;
        if (optparam.msgId == '') {
            optparam.msgId = getUuid(32, 32);
        }
        try {
            wx.getNetworkType({
				success: function (res) {
					net = {
						appid: data.appId,
						msgid: optparam.msgId,
						netType: res.networkType,
						message: '鑾峰彇鎴愬姛'
					}
					data.success(net);
				},
				fail: function (res) {
					net = {
						appid: data.appId,
						msgid: optparam.msgId,
						netType: '',
						message: '鑾峰彇澶辫触'
					}
					data.error(net);
				}

			})
        } catch (e) { }
    },
    getTokenInfo: function (opt) {
        var _this = this;
        if (!optparam.isLoading) {
            return;
        }
        for (let key in optparam['jssdkLog']) {
            optparam['jssdkLog'][key] = ''
        }
        optparam.isLoading = false;
        optparam.ywType = 'CT';

        optparam.msgId = opt.data.traceId;
        let options = {
            version: opt.data.version,
            //涓氬姟鏂瑰弬鏁�
            appId: opt.data.appId,
            openType: opt.data.openType,
            expandParams: opt.data.expandParams,
            isTest: opt.data.isTest,
            sign: opt.data.sign,
            succ: opt.success,
            err: opt.error,
            traceId: opt.data.traceId,
            msgId: opt.data.traceId,
            timestamp: opt.data.timestamp,
            authPageType: opt.data.authPageType,
            //鍏叡鍙傛暟
            userInformation: optparam.userInformation,
            wxappid: wx.getAccountInfoSync().miniProgram.appId,
            businessType: optparam.businessType
        }
        optparam['jssdkLog']['appid'] = options.appId;
        optparam['jssdkLog']['appScene'] = '1';
        optparam['jssdkLog']['traceid'] = options.traceId;
        optparam['jssdkLog']['wxappid'] = options.wxappid;
        optparam['jssdkLog']['clientType'] = wx.getSystemInfoSync().platform;
        wx.getNetworkType({
			success: function (res) {
				if (res.networkType == 'wifi') {
					optparam['jssdkLog']['networkType'] = res.networkType;
					var error = {
						code: '504',
						message: '缃戠粶鐜涓嶆敮鎸佸彇鍙�',
						msgId: options.msgId
					}
					optparam.isLoading = true;
					options.err(error);

				} else {

					_this.getYDPhoneNumber(options);
				}
			},
			fail: function (res) {
				net = {
					appid: data.appId,
					msgid: optparam.msgId,
					netType: '',
					message: '鑾峰彇缃戠粶鐜澶辫触'
				}
				data.error(net);
			}

		})
        // _this.getYDPhoneNumber(options);
    },
    getYDPhoneNumber: function (options) {
        var _this = this;

        //缁勮璇锋眰鍙傛暟
        var param = {
            // header: {
            version: options.version,
            timestamp: options.timestamp,
            appId: options.appId,
            businessType: options.businessType,
            traceId: options.traceId,
            // },
            // body: {
            sign: options.sign,
            msgId: options.msgId,
            userInformation: options.userInformation,
            expandParams: options.expandParams,
            wxappid: options.wxappid
            // }
        }
        let reqUrl = options.isTest === '0' ? optparam.httpsPreGetmobile.test01 : optparam.httpsPreGetmobile.pro;
        optparam['jssdkLog']['CMrequestTime_PreGetmobile'] = dateFormat(new Date(), "yyyyMMddhhmmssSSS");

        wx.request({
            url: reqUrl,
            data: JSON.stringify(param),
            method: 'POST',
            header: {
                'content-type': 'application/json'
            },
            success(res) {
                res = res.data.body;
                optparam['jssdkLog']['CMresponseTime_PreGetmobile'] = dateFormat(new Date(), "yyyyMMddhhmmssSSS");
                optparam['jssdkLog']['CM_resultCode'] = res.resultCode;
                if (res.operatorNetData) {
                    optparam.operatorNetData = res.operatorNetData;
                }else {
					optparam.operatorNetData = "";
				}
                if (res.resultCode === '103000') {
                    var option = {
                        resultCode: res.resultCode,
                        authPageUrl: res.authPageUrl,
                        traceId: options.traceId,
                        accessToken: res.accessToken,
                        maskPhone: res.maskPhone,
                        authLevel: res.authLevel,
                        appName: res.appName,
                        userInformation: options.userInformation,
                        appId: options.appId,
                        expandParams: options.expandParams,
                        isTest: options.isTest,
                        succ: options.succ,
                        err: options.err,
                        customerPrivacyConfig: res.customerPrivacyConfig,
                        oper: 'CM',
                        authPageType: options.authPageType
                    }
                    _this.getAuthentication(option)
                } else {
                    options.YDData = {
                        code: res.resultCode,
                        message: res.resultDesc
                    }
                    _this.getYWpre(options);

                }

            },
            fail(res) {
                optparam['jssdkLog']['CMresponseTime_PreGetmobile'] = dateFormat(new Date(), "yyyyMMddhhmmssSSS");
                optparam['jssdkLog']['CM_resultCode'] = '500';
                options.YDData = {
                    code: '500',
                    message: '缃戠粶寮傚父锛岃妫€鏌ョ綉缁滆缃�'
                }
                _this.getYWpre(options);
            }
        })
    },
    // 寮傜綉棰勫彇鍙�
    getYWpre: function (opt) {
        var _this = this;
        var encrypted = getUuid(16, 16);

        var keyStr = hex_md5(encrypted).substr(8, 16).toUpperCase();
        var mobilesystem = getSystem();

        var sign = hex_md5(opt.appId + '1.0' + opt.msgId + opt.timestamp).toLowerCase();

        var reqdata = {
            ver: '1.0',
            appId: opt.appId,
            interfaceVersion: '1.0',
            expandParams: opt.expandParams,
            msgId: opt.msgId,
            timestamp: opt.timestamp,
            mobilesystem: mobilesystem,
            wxappid: opt.wxappid,
            sign: sign
        }
        reqdata = JSON.stringify(reqdata);
        reqdata = CryptoJS.encrypt(reqdata, keyStr, '0000000000000000');

        var param = {
            header: {
                appId: opt.appId,
                interfaceVersion: opt.version,
                traceId: opt.traceId,
                'content-type': 'application/json'
            },
            body: {
                encrypted: encrypted,
                reqdata: reqdata,
                businessType: opt.businessType,
                wxappid: opt.wxappid,
            }

        }
        if (optparam.ywType == "CT") {
            var reqUrl = opt.isTest === '0' ? optparam.getTelecomUrl.test01 : optparam.getTelecomUrl.pro;
            optparam['jssdkLog']['CTrequestTime_PreGetmobile'] = dateFormat(new Date(), "yyyyMMddhhmmssSSS");
        } else if (optparam.ywType == "CU") {
            var reqUrl = opt.isTest === '0' ? optparam.getUnicomUrl.test01 : optparam.getUnicomUrl.pro;
            optparam['jssdkLog']['CUrequestTime_PreGetmobile'] = dateFormat(new Date(), "yyyyMMddhhmmssSSS");

        }

        wx.request({
            url: reqUrl,
            header: param.header,
            data: JSON.stringify(param.body),
            method: 'POST',
            success(res) {
                res = res.data;
                if (res.resultCode == '103000') {
                    _this.getYW(opt, res.data)
                } else if (res.resultCode != '103000' && optparam.ywType == "CT") {
                    optparam['jssdkLog']['CTresponseTime_PreGetmobile'] = dateFormat(new Date(), "yyyyMMddhhmmssSSS");
                    optparam['jssdkLog']['CT_resultCode'] = res.resultCode;
                    opt.CTData = {
                        code: res.resultCode,
                        message: res.desc
                    }
                    optparam.ywType = "CU";
                    _this.getYWpre(opt);


                } else {
                    optparam['jssdkLog']['CUresponseTime_PreGetmobile'] = dateFormat(new Date(), "yyyyMMddhhmmssSSS");
                    optparam['jssdkLog']['CU_resultCode'] = res.resultCode;
                    opt.CUData = {
                        code: res.resultCode,
                        message: res.desc
                    }
                    var error = {
                        msgId: opt.msgId,
                        CUData: opt.CUData,
                        CTData: opt.CTData,
                        YDData: opt.YDData
                    }
                    optparam.isLoading = true;
                    if (optparam.operatorNetData) {
                        error.operatorNetData = optparam.operatorNetData;
                    }
                    opt.err(error);
                    _this.getLog();
                }

            },
            fail(res) {
                if (optparam.ywType == "CT") {
                    optparam['jssdkLog']['CTresponseTime_PreGetmobile'] = dateFormat(new Date(), "yyyyMMddhhmmssSSS");
                    optparam['jssdkLog']['CT_resultCode'] = '500';
                    opt.CTData = {
                        code: '500',
                        message: '缃戠粶寮傚父锛岃妫€鏌ョ綉缁滆缃�'
                    }
                    optparam.ywType = "CU";
                    _this.getYWpre(opt);
                } else {
                    optparam['jssdkLog']['CUresponseTime_PreGetmobile'] = dateFormat(new Date(), "yyyyMMddhhmmssSSS");
                    optparam['jssdkLog']['CU_resultCode'] = '500';
                    opt.CUData = {
                        code: '500',
                        message: '缃戠粶寮傚父锛岃妫€鏌ョ綉缁滆缃�'
                    }
                    var error = {
                        msgId: opt.msgId,
                        CUData: opt.CUData,
                        CTData: opt.CTData,
                        YDData: opt.YDData
                    }
                    optparam.isLoading = true;
                    if (optparam.operatorNetData) {
                        error.operatorNetData = optparam.operatorNetData;
                    }
                    opt.err(error)
                    _this.getLog();
                }
            }
        })

    },
    // 寮傜綉鍙栧彿
    getYW: function (opt, reqUrl) {
        var _this = this;
        wx.request({
            url: reqUrl,
            method: 'GET',
            success(res) {

                res = res.data;
                console.log(res)
                if (JSON.stringify(res).indexOf("(") > 0) {
                    var ds = JSON.parse(res.match(/\(([^)]*)\)/)[1]);
                } else {
                    var ds = res;
                }
                if (ds.result == '0') {
                    _this.getYWcb(opt, ds.data)
                } else {
                    if (optparam.ywType == "CT") {
                        optparam['jssdkLog']['CTresponseTime_PreGetmobile'] = dateFormat(new Date(), "yyyyMMddhhmmssSSS");
                        optparam['jssdkLog']['CT_resultCode'] = ds.result.toString();
                        opt.CTData = {
                            code: ds.result.toString(),
                            message: ds.data
                        }
                        optparam.ywType = "CU";
                        _this.getYWpre(opt);
                    } else {
                        optparam['jssdkLog']['CUresponseTime_PreGetmobile'] = dateFormat(new Date(), "yyyyMMddhhmmssSSS");
                        optparam['jssdkLog']['CU_resultCode'] = ds.code;
                        //杩斿洖閿欒
                        opt.CUData = {
                            code: ds.code,
                            message: ds.msg,
                            result: ds.result,
                        }
                        var error = {
                            msgId: opt.msgId,
                            CUData: opt.CUData,
                            CTData: opt.CTData,
                            YDData: opt.YDData
                        }
                        optparam.isLoading = true;
                        if (optparam.operatorNetData) {
                            error.operatorNetData = optparam.operatorNetData;
                        }
                        opt.err(error)
                        _this.getLog();
                    }

                }
            },
            fail(res) {
                if (optparam.ywType == "CT") {
                    optparam['jssdkLog']['CTresponseTime_PreGetmobile'] = dateFormat(new Date(), "yyyyMMddhhmmssSSS");
                    optparam['jssdkLog']['CT_resultCode'] = '500';
                    opt.CTData = {
                        code: '500',
                        message: '缃戠粶寮傚父锛岃妫€鏌ョ綉缁滆缃�'
                    }
                    optparam.ywType = "CU";
                    _this.getYWpre(opt);
                } else {
                    optparam['jssdkLog']['CUresponseTime_PreGetmobile'] = dateFormat(new Date(), "yyyyMMddhhmmssSSS");
                    optparam['jssdkLog']['CU_resultCode'] = '500';
                    opt.CUData = {
                        code: '500',
                        message: '缃戠粶寮傚父锛岃妫€鏌ョ綉缁滆缃�'
                    }
                    var error = {
                        msgId: opt.msgId,
                        CUData: opt.CUData,
                        CTData: opt.CTData,
                        YDData: opt.YDData
                    }
                    optparam.isLoading = true;
                    if (optparam.operatorNetData) {
                        error.operatorNetData = optparam.operatorNetData;
                    }
                    opt.err(error);
                    _this.getLog();
                }
            }
        })

    },
    // 寮傜綉鍙栧彿鍥炶皟
    getYWcb: function (opt, data) {
        var _this = this;
        var param = {
            header: {
                appId: opt.appId,
                interfaceVersion: opt.version,
                traceId: opt.traceId,
                businessType: opt.businessType,
                timestamp: opt.timestamp,
                wxappid: opt.wxappid,
                'content-type': 'application/json'
            },
            body: {
                data: data,
                ver: "1.0",
                userInformation: opt.userInformation
            }

        }
        if (optparam.ywType == "CT") {
            var reqUrl = opt.isTest === '0' ? optparam.getTelecomToken.test01 : optparam.getTelecomToken.pro;
        } else if (optparam.ywType == "CU") {
            var reqUrl = opt.isTest === '0' ? optparam.getUnicomToken.test01 : optparam.getUnicomToken.pro;
        }
        wx.request({
            url: reqUrl,
            header: param.header,
            data: JSON.stringify(param.body),
            method: 'POST',
            success(res) {
                res = res.data;
                if (optparam.ywType == "CT") {
                    optparam['jssdkLog']['CTresponseTime_PreGetmobile'] = dateFormat(new Date(), "yyyyMMddhhmmssSSS");
                    optparam['jssdkLog']['CT_resultCode'] = res.resultCode;
                } else {
                    optparam['jssdkLog']['CUresponseTime_PreGetmobile'] = dateFormat(new Date(), "yyyyMMddhhmmssSSS");
                    optparam['jssdkLog']['CU_resultCode'] = res.resultCode;
                }
                if (res.resultCode == '103000' && res.accessToken != "") {

                    var option = {
                        resultCode: res.resultCode,
                        authPageUrl: res.authPageUrl,
                        traceId: opt.traceId,
                        accessToken: res.accessToken,
                        maskPhone: res.maskPhone,
                        authLevel: res.authLevel,
                        appName: res.appName,
                        userInformation: opt.userInformation,
                        appId: opt.appId,
                        expandParams: opt.expandParams,
                        isTest: opt.isTest,
                        succ: opt.succ,
                        err: opt.err,
                        oper: optparam.ywType,
                        customerPrivacyConfig: res.customerPrivacyConfig,
                        authPageType: opt.authPageType
                    }
                    _this.getAuthentication(option)
                } else {
                    if (optparam.ywType == "CT") {
                        opt.CTData = {
                            code: '',
                            message: ''
                        }
                        opt.CTData.code = res.resultCode == '103000' ? '502' : res.resultCode;
                        opt.CTData.message = res.resultCode == '103000' ? '鐢典俊鍙栧彿鑳藉姏鍏抽棴' : res.desc;

                        var error = {
                            msgId: opt.msgId,
                            CUData: {},
                            CTData: opt.CTData,
                            YDData: opt.YDData
                        }
                        optparam.isLoading = true;
                        if (optparam.operatorNetData) {
                            error.operatorNetData = optparam.operatorNetData;
                        }
                        opt.err(error);
                        _this.getLog();
                    } else {
                        opt.CUData = {
                            code: '',
                            message: ''
                        }
                        opt.CUData.code = res.resultCode == '103000' ? '502' : res.resultCode;
                        opt.CUData.message = res.resultCode == '103000' ? '鑱旈€氬彇鍙疯兘鍔涘叧闂�' : res.desc

                        var error = {
                            msgId: opt.msgId,
                            CUData: opt.CUData,
                            CTData: opt.CTData,
                            YDData: opt.YDData
                        }
                        optparam.isLoading = true;
                        if (optparam.operatorNetData) {
                            error.operatorNetData = optparam.operatorNetData;
                        }
                        opt.err(error);
                        _this.getLog();

                    }
                }

            },
            fail(res) {
                if (optparam.ywType == "CT") {
                    optparam['jssdkLog']['CTresponseTime_PreGetmobile'] = dateFormat(new Date(), "yyyyMMddhhmmssSSS");
                    optparam['jssdkLog']['CT_resultCode'] = '500';
                    opt.CTData = {
                        code: '500',
                        message: '缃戠粶寮傚父锛岃妫€鏌ョ綉缁滆缃�'
                    }
                    var error = {
                        msgId: opt.msgId,
                        CUData: {},
                        CTData: opt.CTData,
                        YDData: opt.YDData
                    }
                    optparam.isLoading = true;
                    if (optparam.operatorNetData) {
                        error.operatorNetData = optparam.operatorNetData;
                    }
                    opt.err(error);
                    _this.getLog();
                } else {
                    optparam['jssdkLog']['CUresponseTime_PreGetmobile'] = dateFormat(new Date(), "yyyyMMddhhmmssSSS");
                    optparam['jssdkLog']['CU_resultCode'] = '500';
                    opt.CUData = {
                        code: '500',
                        message: '缃戠粶寮傚父锛岃妫€鏌ョ綉缁滆缃�'
                    }
                    var error = {
                        msgId: opt.msgId,
                        CUData: opt.CUData,
                        CTData: opt.CTData,
                        YDData: opt.YDData
                    }
                    if (optparam.operatorNetData) {
                        error.operatorNetData = optparam.operatorNetData;
                    }
                    optparam.isLoading = true;
                    opt.err(error);
                    _this.getLog();
                }
            }
        })

    },
    getAuthentication(option) {
        var _this = this;
        if (!!option.authPageUrl && !!option.authLevel && !!option.accessToken && option.authLevel != '5') {
            var url = getCurUrl();
            var authUrl = option.authPageUrl +
                '?traceId=' + option.traceId +
                '&accessToken=' + option.accessToken +
                "&maskPhone=" + option.maskPhone +
                "&authLevel=" + option.authLevel +
                "&authName=" + option.appName +
                "&userInformation=" + option.userInformation +
                "&appId=" + option.appId +
                "&expandParams=" + option.expandParams +
                "&isTest=" + option.isTest +
                "&oper=" + option.oper +
                "&cur=" + url +
                "&authPageType=" + option.authPageType +
                "&v=" + optparam.v;
            if (isJSON(option.customerPrivacyConfig) && option.authPageType != '3') {
                authUrl += "&customerPrivacyConfig=" + encodeURIComponent(option.customerPrivacyConfig)
            } else if (option.authPageType == '3' && optparam.authPageOpt) {
                authUrl += "&pageOption=" + encodeURIComponent(JSON.stringify(optparam.authPageOpt))
            }
            if (optparam.operatorNetData) {
                authUrl += "&operatorNetData=" + encodeURIComponent(JSON.stringify(optparam.operatorNetData))
            }
            optparam.isLoading = true;
            var obj = {
                code: option.resultCode,
                authUrl: authUrl
            }
            if (optparam.operatorNetData) {
                obj.operatorNetData = optparam.operatorNetData;
            }
            option.succ(obj)
            _this.getLog();
        } else if (!!option.authPageUrl && !!option.authLevel && !!option.accessToken && option.authLevel == '5') {
            optparam.maskPhone = option.maskPhone;
            let obj = {
                code: option.resultCode,
                oper: option.oper,
                maskPhone: option.maskPhone,
                accessToken: option.accessToken,
                traceId: option.traceId,
                message: '鑾峰彇AccessToken鎴愬姛'
            }
            if (optparam.operatorNetData) {
                obj.operatorNetData = optparam.operatorNetData;
            }
            optparam.isLoading = true;
            option.succ(obj)
            _this.getLog();
        } else {
            var error = {
                code: '503',
                message: '鍙傛暟缂哄け',
                msgId: option.traceId
            }
            optparam.isLoading = true;
            option.err(error);
            _this.getLog();
        }

    },
    authGetToken: function (opt) {
        var maskPhone = opt.data.maskPhone ? opt.data.maskPhone : optparam.maskPhone;
        var str = maskPhone.replace(/\*+/g, opt.data.maskVal);
        var phone = hex_md5(str);
        optparam.authGetTokenSucc = 'undefined' === typeof opt.success ? function () { } : opt.success;
        optparam.authGetTokenErr = 'undefined' === typeof opt.error ? function () { } : opt.error;
        var param = {
            header: {
                interfaceVersion: opt.data.version,
                timestamp: dateFormat(new Date(), "yyyyMMddhhmmssSSS"),
                appId: opt.data.appId,
                businessType: optparam.businessType,
                traceId: opt.data.traceId,
                'Content-Type': 'application/json',
            },
            body: {
                wxappid: wx.getAccountInfoSync().miniProgram.appId,
                accessToken: opt.data.accessToken,
                phone: phone,
                userInformation: optparam.userInformation,
                expandParams: opt.data.expandParams
            }
        }
        var reqUrl = opt.data.isTest === '0' ? optparam.getToken.test01 : optparam.getToken.pro;
        wx.request({
            url: reqUrl,
            data: JSON.stringify(param.body),
            method: 'POST',
            header: param.header,
            success(res) {
                if (res.data.resultCode == '103000') {
                    var obj = {
                        code: res.data.resultCode,
                        message: res.data.desc,
                        msgId: opt.data.traceId,
                        token: res.data.data.token,
                        userInformation: optparam.userInformation
                    }
                    optparam.authGetTokenSucc(obj)
                } else {
                    var obj = {
                        code: res.data.resultCode,
                        message: res.data.desc,
                        msgId: opt.data.traceId,
                    }
                    optparam.authGetTokenErr(obj)
                }
            },
            fail(res) {

            }
        })
    },
    getLog() {
        var version = '2.0';
        var appId = optparam['jssdkLog']['appid'];
        var timestamp = dateFormat(new Date(), "yyyyMMddhhmmssSSS");
        var str = version + appId + timestamp + optparam['jssdkLog']['traceid'] + '@Fdiwmxy7CBDDQNUI';
        var signMD5 = hex_md5(str);
        var param = {
            "header": {
                "sign": signMD5,
                "msgid": optparam['jssdkLog']['traceid'],
                "version": version,
                "appid": appId,
                "systemtime": timestamp
            },
            "body": {
                "log": optparam['jssdkLog']
            }
        }
        var reqUrl = optparam.logReport.pro;
        wx.request({
            url: reqUrl,
            data: JSON.stringify(param),
            method: 'POST',
            header: {
                'content-type': 'application/json'
            },
            success(res) {

            },
            fail(res) {

            }
        })

    }
};
let YDRZ = {};
export default YDRZ = {
    getTokenInfo: function (opt) {
        getToken.getTokenInfo(opt);
    },
    authPageInit: function (setOpt) {
        optparam.authPageOpt = setOpt;
        console.log(optparam.authPageOpt)
    },
    authGetToken: function (opt) {
        getToken.authGetToken(opt);
    },
    getConnection: function (data) {
        getToken.getConnection(data);
    }

};